﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EEG_NIRS_Record
{
    class OpticsProcess
    {
        public int counter;
        double fs, fc1, fc2;
        IIRFilter[] iir;
        public OpticsProcess(double fs, double fc1, double fc2)
        {
            counter = 0;
            this.fs = fs;
            this.fc1 = fc1;
            this.fc2 = fc2;
            iir = new IIRFilter[4];
            for (int i = 0; i < 4; i++)
            {
                iir[i] = new IIRFilter();
            }
        }
        public double[] Demodulate(int data)
        {
            double[] light = new double[2];
            double I, Q;
            double[] sin_data = new double[2];
            double[] cos_data = new double[2];

            sin_data[0] = data * Math.Sin(counter * 2 * Math.PI * fc1 / fs);
            Q = iir[0].IIR_Filter(sin_data[0]);
            cos_data[0] = data * Math.Cos(counter * 2 * Math.PI * fc1 / fs);
            I = iir[1].IIR_Filter(cos_data[0]);
            light[0] = Math.Sqrt(I * I + Q * Q);
            sin_data[1] = data * Math.Sin(counter * 2 * Math.PI * fc2 / fs);
            Q = iir[2].IIR_Filter(sin_data[1]);
            cos_data[1] = data * Math.Cos(counter * 2 * Math.PI * fc2 / fs);
            I = iir[3].IIR_Filter(cos_data[1]);
            light[1] = Math.Sqrt(I * I + Q * Q);

            counter++;
            if (counter == 66660)
            {
                counter = 0;
            }

            return light;
        }
        public Hbr mes2hb(double[] data, double[] baseline)
        {
            Hbr hbr = new Hbr();
            double eoxy_730 = 0.1174066;
            double eoxy_850 = 0.2525936;
            double edeo_730 = 0.2976843;
            double edeo_850 = 0.1798319;
            double a_690 = 0.0;
            double a_830 = 0.0;
            double hb = 0.0;
            double hbo = 0.0;
            double hbt = 0.0;
            if ((data[0] * baseline[0]) > 0)
            {
                a_690 = Math.Log(baseline[0] / data[0]);
            }
            if ((data[1] * baseline[1]) > 0)
            {
                a_830 = Math.Log(baseline[1] / data[1]);
            }
            if ((eoxy_730 * edeo_850 - eoxy_850 * edeo_730) != 0)
            {
                hbo = (a_690 * edeo_850 - a_830 * edeo_730) / (eoxy_730 * edeo_850 - eoxy_850 * edeo_730);
            }
            if ((edeo_730 * eoxy_850 - edeo_850 * eoxy_730) != 0)
            {
                hb = (a_690 * eoxy_850 - a_830 * eoxy_730) / (edeo_730 * eoxy_850 - edeo_850 * eoxy_730);
            }
            hbt = hbo + hb;
            hbr.hb = hb;
            hbr.hbo = hbo;
            hbr.hbt = hbt;
            return hbr;
        }
    }
}
